/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package de.adorsys.ohos.securestoragelibrary;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

/**
 * Preference程序退出后就无法读取存储的值,原因是context不一致
 *
 * @since 2021-05-19
 */
public class PreferenceUtils {
    private static final String PREFERENCE_FILE_NAME = "fileName";

    private static PreferenceUtils instance = null;

    private PreferenceUtils() {
    }

    /**
     * 静态锁对象
     *
     * @return Utils
     */
    public static synchronized PreferenceUtils getInstance() {
        if (instance == null) {
            instance = new PreferenceUtils();
        }
        return instance;
    }

    /**
     * 存放key和value
     *
     * @param context
     * @param key
     * @param value
     */
    public static void putString(Context context, String key, String value) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME);
        preferences.putString(key, value);
        preferences.flushSync();
    }

    /**
     * 根据key获取value
     *
     * @param context
     * @param key
     * @return String获取的String默认值为:null
     */
    public static String getString(Context context, String key) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME);
        String value = preferences.getString(key, null);
        return value;
    }

    /**
     * 根据key获取value
     *
     * @param context
     * @param key
     */
    public static void deleteString(Context context, String key) {
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        Preferences preferences = databaseHelper.getPreferences(PREFERENCE_FILE_NAME);
        preferences.delete(key);
    }
}
